/**
 * Created by maiseries on 2017/10/15.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    Image,
    ScrollView,
    Text,
    TouchableWithoutFeedback,
    TouchableOpacity,
    DeviceEventEmitter,
    Platform,
    StatusBar
} from 'react-native';
import Swiper from 'react-native-swiper'
import DeviceInfo from 'react-native-device-info'

import QuickBtn from '../components/IndexQuickBtn'
import VersionUpdate from '../components/VersionUpdateModal'
import Card from '../components/IndexCardView'
import ATBtn from '../components/AssetTypeIconBtn'
import Refresh from '../components/RefreshControlView'
import Constants from '../config/Constants'
import AssetTypeDict from '../config/dict/AssetTypeStatic'
import SystemService from '../services/System'

let _self = null, _subscription = null;

let _top = 0;

if (Platform.OS === 'ios') {
    if (DeviceInfo.getSystemVersion().split('.')[0] * 1 > 10) {
        _top = -20;
    }
}

class Views extends React.Component {

    constructor(props) {
        super(props);
        _self = this;
        this.state = {
            banners: [],
            assetTypeDetails: [
                {
                    icon: AssetTypeDict["1512549651341"],
                    name: '供应链资产',
                    onPress(){
                        _self.skip('AssetSummary', {type: 3, name: '供应链资产'});
                    }
                }, {
                    icon: AssetTypeDict["1512549677257"],
                    name: '抵质押类',
                    onPress(){
                        _self.skip('AssetSummary', {type: 5, name: '抵质押类'});
                    }
                }, {
                    icon: AssetTypeDict["1512549671473"],
                    name: '企业贷款类',
                    onPress(){
                        _self.skip('AssetSummary', {type: 4, name: '企业贷款类'});
                    }
                }, {
                    icon: AssetTypeDict["1512549691080"],
                    name: '租赁资产',
                    onPress(){
                        _self.skip('AssetSummary', {type: 6, name: '租赁资产'});
                    }
                }, {
                    icon: AssetTypeDict["1512549695449"],
                    name: '公司债权类',
                    onPress(){
                        _self.skip('AssetSummary', {type: 7, name: '公司债权类'});
                    }
                }, {
                    icon: AssetTypeDict["1512549711155"],
                    name: '金融债权类',
                    onPress(){
                        _self.skip('AssetSummary', {type: 10, name: '金融债权类'});
                    }
                }, {
                    icon: AssetTypeDict["1512549776653"],
                    name: '票据类资产',
                    onPress(){
                        _self.skip('AssetSummary', {type: 11, name: '票据类资产'});
                    }
                }, {
                    icon: AssetTypeDict["more"],
                    name: '更多',
                    onPress(){
                        _self.skip('AssetSummaryList');
                    }
                }
            ],
            notices: [],
            messages: false,
            versionUpdate: false
        }
    }

    componentWillMount() {

    }

    componentDidMount() {
        _self.splashAdSkip();
        _self.load();
        _self.message();
        _self.messageListener();
        _self.update();
    }

    componentWillUnmount() {
        _subscription.remove();
    }

    messageListener() {
        _subscription = DeviceEventEmitter.addListener(Constants.LISTENER_MESSAGES, () => _self.message())
    }

    //开屏AD专用跳转监听
    splashAdSkip() {
        setTimeout(() => {
            const route = _self.props.navigation.state.params ? _self.props.navigation.state.params.skipTo : null;
            if (route) {
                _self.skip(route.routeName, route.params);
            }
        }, 400)
    }

    //scroll滚动监听 => navBar属性opacity
    eventOnScroll(event) {
        const opacity = event.contentOffset.y / layout.height(500) > 1 ? 1 : event.contentOffset.y / layout.height(500);
        _self.refs.nav_bar.setNativeProps({
            style: {
                backgroundColor: `rgba(51,56,85,${opacity})`
            }
        })
        _self.refs.nav_bar_title.setNativeProps({
            style: {
                color: `rgba(224,177,91,${opacity})`
            }
        })
    }

    //跳转封装
    skip(route, params) {
        _self.props.navigation.navigate(route, params ? params : {});
    }

    //数据加载
    async load() {
        const {result, message, data} = await SystemService.indexAggregate();
        if (result) {
            _self.setState({
                banners: data.banners,
                notices: data.notices
            })
        } else {
            Toast.show(message);
        }
    }

    async message() {
        const {result, message, data} = await SystemService.aggregateMessage();
        if (result) {
            _self.setState({
                messages: data.message
            })
        } else {
            Toast.show(message);
        }
    }

    update() {
        const updateConfig = global.config;
        if(updateConfig.update){
            _self.setState({
                versionUpdate: updateConfig.version !== updateConfig.update.version
            })
        }
    }

    cancel() {
        _self.setState({
            versionUpdate: false
        })
    }

    render() {
        return (
            <View style={styles.outer}>
                <ScrollView
                    contentInset={{
                        top: _top
                    }}
                    ref="index_scroll_view"
                    onScroll={(e) => this.eventOnScroll(e.nativeEvent)}
                    scrollEventThrottle={1}
                    style={[base.clientWH, styles.container]}>
                    <View style={styles.bannerBox}>
                        {
                            this.state.banners.length > 0 ?
                                <Swiper
                                    paginationStyle={styles.swiperPagination}
                                    dot={<View style={styles.swiperDot}/>}
                                    activeDot={<View style={styles.swiperDotActive}/>}
                                    autoplay={true}
                                    autoplayTimeout={4}>
                                    {
                                        this.state.banners.map((item, index) => {
                                            return (
                                                <View key={index} style={styles.bannerItem}>
                                                    <TouchableWithoutFeedback
                                                        onPress={() => item.url ? this.skip('AdWebView', {
                                                            url: item.url,
                                                            title: item.title
                                                        }) : {}}>
                                                        <Image
                                                            style={styles.banner}
                                                            source={item.src}
                                                            resizeMode={'cover'}/>
                                                    </TouchableWithoutFeedback>
                                                </View>
                                            )
                                        })
                                    }
                                </Swiper> :
                                <View style={styles.bannerItem}>
                                    <Image source={require('../sources/image_index_banner_default.png')}
                                           style={styles.banner}/>
                                </View>
                        }
                    </View>
                    <View style={styles.assetBox}>
                        {
                            this.state.assetTypeDetails.map((item, index) => {
                                return (
                                    <ATBtn
                                        key={index}
                                        style={styles.assetTypeSummary}
                                        onPress={() => item.onPress()}
                                        icon={item.icon}
                                        wrap={4}
                                        text={item.name}/>
                                )
                            })
                        }
                    </View>
                    <Card title="资产公告" style={styles.noticeBox}>
                        <View style={styles.noticeContentBox}>
                            {
                                this.state.notices.length > 0 ?
                                    <Swiper
                                        scrollEnabled={false}
                                        autoplay={true}
                                        autoplayTimeout={5}
                                        loadMinimalSize={3}
                                        showsPagination={false}
                                        horizontal={false}>
                                        {
                                            this.state.notices.map((item, index) => {
                                                return (
                                                    <View key={index}>
                                                        {
                                                            item.map((childrenItem, childrenIndex) => {
                                                                return (
                                                                    <View key={childrenIndex}
                                                                          style={styles.noticeContentItem}>
                                                                        <Image
                                                                            style={styles.noticeContentIcon}
                                                                            resizeMode={'contain'}
                                                                            source={require('../sources/icon_index_notice.png')}/>
                                                                        <View style={styles.noticeContentTextBox}>
                                                                            <Text
                                                                                style={styles.noticeContentText}>{format.subStr(childrenItem.notice_content, 25)}</Text>
                                                                            <Text
                                                                                style={styles.noticeContentText}>{childrenItem.show_date}</Text>
                                                                        </View>
                                                                    </View>
                                                                )
                                                            })
                                                        }
                                                    </View>
                                                )
                                            })
                                        }
                                    </Swiper> :
                                    <TouchableWithoutFeedback onPress={() => this.load()}>
                                        <View style={[base.rowCC, styles.noticeNoDataBox]}>
                                            <Text allowFontScaling={false} style={styles.noticeNoData}>数据加载失败，请点击重试!</Text>
                                        </View>
                                    </TouchableWithoutFeedback>
                            }
                        </View>
                    </Card>
                    <Card title="麦乐服务" style={styles.serviceBox}>
                        <View style={[base.rowCC, styles.serviceRow, {
                            borderBottomWidth: layout.LINE_WIDTH,
                            borderBottomColor: '#f3f3f1'
                        }]}>
                            <TouchableOpacity
                                activeOpacity={layout.TOUCH_OPACITY_ACTIVE}
                                onPress={() => this.skip('AssetSummaryList')}>
                                <View style={[styles.serviceItem, {
                                    borderRightWidth: layout.LINE_WIDTH,
                                    borderRightColor: '#f3f3f1'
                                }]}>
                                    <Image
                                        style={styles.serviceIcon}
                                        source={require('../sources/icon_index_card_1.png')}
                                        resizeMode={'contain'}/>
                                    <View style={styles.serviceTextBox}>
                                        <Text allowFontScaling={false} style={styles.serviceText}>项目融资</Text>
                                        <Text allowFontScaling={false} style={styles.serviceTextSub}>量身定做项目融资方案</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity
                                activeOpacity={layout.TOUCH_OPACITY_ACTIVE}
                                onPress={() => this.skip('AboutMai')}>
                                <View style={[styles.serviceItem]}>
                                    <Image
                                        style={styles.serviceIcon}
                                        source={require('../sources/icon_index_card_2.png')}
                                        resizeMode={'contain'}/>
                                    <View style={styles.serviceTextBox}>
                                        <Text allowFontScaling={false} style={styles.serviceText}>专业服务</Text>
                                        <Text allowFontScaling={false} style={styles.serviceTextSub}>专业团队优质服务</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={[base.rowCC, styles.serviceRow]}>
                            <TouchableOpacity
                                activeOpacity={layout.TOUCH_OPACITY_ACTIVE}
                                onPress={() => this.skip('DataSupport')}>
                                <View style={[styles.serviceItem, {
                                    borderRightWidth: layout.LINE_WIDTH,
                                    borderRightColor: '#f3f3f1'
                                }]}>
                                    <Image
                                        style={styles.serviceIcon}
                                        source={require('../sources/icon_index_card_3.png')}
                                        resizeMode={'contain'}/>
                                    <View style={styles.serviceTextBox}>
                                        <Text allowFontScaling={false} style={styles.serviceText}>数据支持</Text>
                                        <Text allowFontScaling={false} style={styles.serviceTextSub}>多维数据分析评价体系</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity
                                activeOpacity={layout.TOUCH_OPACITY_ACTIVE}
                                onPress={() => this.skip('LawList')}>
                                <View style={[styles.serviceItem]}>
                                    <Image
                                        style={styles.serviceIcon}
                                        source={require('../sources/icon_index_card_4.png')}
                                        resizeMode={'contain'}/>
                                    <View style={styles.serviceTextBox}>
                                        <Text allowFontScaling={false} style={styles.serviceText}>法律法规</Text>
                                        <Text allowFontScaling={false} style={styles.serviceTextSub}>最新政策法规解读</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </Card>
                    <Card>
                        <View style={styles.topicBox}>
                            <TouchableWithoutFeedback onPress={() => this.skip('SubjectDetail', {id: '1'})}>
                                <Image style={styles.topic} source={require('../sources/image_index_topic_years.png')}
                                       resizeMode={'cover'}/>
                            </TouchableWithoutFeedback>
                        </View>
                    </Card>
                    <View style={{height: layout.BOTTOM_TAB_HEIGHT}}/>
                </ScrollView>
                <QuickBtn click={() => this.skip('BusinessForm')}/>
                <View ref="nav_bar" style={[base.rowCC, styles.navContainer, styles.navBarBox]}>
                    <StatusBar barStyle={'light-content'}/>
                    <View style={[base.rowCC, styles.btnBox]}/>
                    <View style={[base.rowCC, styles.titleBox]}>
                        <Text allowFontScaling={false} ref="nav_bar_title" style={styles.title}>{Constants.APP_NAME}</Text>
                    </View>
                    <TouchableWithoutFeedback
                        onPress={() => this.skip('MessageList')}>
                        <View style={[base.rowCC, styles.btnBox]}>
                            <Image
                                style={styles.btnIcon}
                                source={require('../sources/icon_index_message.png')}
                                resizeMode={'contain'}
                            >
                                {
                                    this.state.messages ? <View style={styles.point}/> : <View/>
                                }
                            </Image>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
                <VersionUpdate cancel={() => this.cancel()} visible={this.state.versionUpdate}/>
            </View>
        )
    }

}

const navStyle = {
    navContainer: {
        width: layout.MAX_WIDTH,
        height: layout.STATUS_BAR_HEIGHT + layout.NAV_BAR_HEIGHT,
        paddingTop: layout.STATUS_BAR_HEIGHT,
        backgroundColor: layout.MAIN_AUX_COLOR
    },
    btnBox: {
        alignSelf: 'stretch',
        width: layout.NAV_BAR_HEIGHT
    },
    btnIcon: {
        width: layout.width(50),
        height: layout.height(50),
    },
    titleBox: {
        flex: 1,
    },
    title: {
        color: 'rgba(0,0,0,0)',
        fontSize: layout.font(34)
    },
    point: {
        position: 'absolute',
        right: 0,
        top: 0,
        width: layout.width(14),
        height: layout.height(14),
        borderRadius: layout.width(7),
        backgroundColor: '#FF3C4B'
    }
};

const styles = StyleSheet.create({
    ...navStyle,
    outer: {
        backgroundColor: layout.MAIN_BACKGROUND_COLOR
    },
    container: {},
    navBarBox: {
        position: 'absolute',
        top: 0,
        left: 0,
        backgroundColor: 'rgba(0,0,0,0)'
    },
    bannerBox: {
        width: layout.MAX_WIDTH,
        height: layout.height(380),
    },
    bannerItem: {
        width: layout.MAX_WIDTH,
        height: layout.height(380),
    },
    banner: {
        width: layout.MAX_WIDTH,
        height: layout.height(380)
    },
    swiperPagination: {
        bottom: layout.height(20)
    },
    swiperDotActive: {
        marginHorizontal: layout.width(4),
        width: layout.width(28),
        height: layout.height(8),
        backgroundColor: layout.MAIN_COLOR
    },
    swiperDot: {
        marginHorizontal: layout.width(4),
        width: layout.width(28),
        height: layout.height(8),
        backgroundColor: layout.MAIN_AUX_COLOR
    },
    assetBox: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginBottom: layout.GAP_VERTICAL_MID,
        width: layout.MAX_WIDTH,
        paddingVertical: layout.GAP_VERTICAL_SMALL,
        backgroundColor: '#fff'
    },
    assetTypeSummary: {
        height: layout.height(150),
    },
    noticeContentBox: {
        width: layout.MAX_WIDTH,
        height: layout.height(290),
        paddingHorizontal: layout.GAP_HORIZONTAL_LARGE,
        paddingVertical: layout.GAP_VERTICAL_SMALL
    },
    noticeContentItem: {
        flexDirection: 'row',
        height: layout.height(90),
        paddingVertical: layout.height(15)
    },
    noticeContentIcon: {
        marginTop: layout.height(7),
        marginRight: layout.GAP_HORIZONTAL_SMALL,
        width: layout.width(14),
        height: layout.height(14),
    },
    noticeContentTextBox: {
        flex: 1,
    },
    noticeContentText: {
        color: '#656565',
        fontSize: layout.font(24)
    },
    noticeNoDataBox: {
        flex: 1,
        alignSelf: 'stretch'
    },
    noticeNoData: {
        fontSize: layout.font(28),
        color: layout.FORM_AUX_FONT_COLOR
    },
    serviceRow: {
        width: layout.MAX_WIDTH,
    },
    serviceItem: {
        flexDirection: 'row',
        alignItems: 'center',
        width: layout.MAX_WIDTH / 2,
        height: layout.height(120),
        paddingLeft: layout.GAP_HORIZONTAL_LARGE
    },
    serviceIcon: {
        width: layout.width(58),
        height: layout.height(58),
    },
    serviceTextBox: {
        paddingLeft: layout.GAP_HORIZONTAL_MID
    },
    serviceText: {
        marginBottom: layout.GAP_VERTICAL_SMALL,
        color: '#333333',
        fontSize: layout.font(28)
    },
    serviceTextSub: {
        color: '#737373',
        fontSize: layout.font(20)
    },
    topicBox: {
        paddingHorizontal: layout.width(25),
        paddingVertical: layout.height(22)
    },
    topic: {
        width: layout.width(700),
        height: layout.height(280)
    }
});

//路由
const Index = {
    screen: Views,
    path: 'app/index',
    navigationOptions: {
        header: null,
        tabBarLabel: '首页',
        tabBarIcon: ({focused, tintColor}) => (
            focused ? <Image
                source={require('../sources/icon_tab_index_selected.png')}
                style={{
                    width: layout.width(60),
                    height: layout.height(60)
                }}
                resizeMode={'contain'}
            /> : <Image
                source={require('../sources/icon_tab_index_unselect.png')}
                style={{
                    width: layout.width(60),
                    height: layout.height(60)
                }}
                resizeMode={'contain'}
            />
        ),
    },
    name: 'Index',
    sign: false
};

export default Index;